package com.heima.wemedia.config;


import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.WmThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义过滤器
 */
@Slf4j
public class WebMvcInterceptor implements HandlerInterceptor {
    /**
     * 发放执行之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取token
        String token = request.getHeader("token");
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        Integer userId = (Integer) claimsBody.get("id");

        //封装数据
        WmUser wmUser = new WmUser();
        wmUser.setId(userId);
        WmThreadLocal.setWmUser(wmUser);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        WmThreadLocal.removeWmuser();
    }
}

